﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using Project.Dal.Base;
using System.Configuration;
using System.ServiceModel.Configuration;
using System.ServiceModel.Description;
using CNDreams.Server.Base;
using System.Reflection;
using Project.Server.Base;
using System.ServiceModel.Channels;

namespace CNDreams.Server
{
	class Program
	{
		static void Main(string[] args)
		{
			NHibernateHelper.Configure();
			List<ServiceHost> hosts = new List<ServiceHost>();
			try
			{
				WSHttpBinding wsHttpBinding = new WSHttpBinding("LargeBuffer");
				Assembly assemblyInterfaces = Assembly.Load("CNDreams.ServiceInterface");
				Type[] allInterfaceTypes = assemblyInterfaces.GetTypes();
				Type[] allServerTypes = Assembly.GetExecutingAssembly().GetTypes();
				for (int i = 0; i < allInterfaceTypes.Count(); i++)
				{
					if (!allInterfaceTypes[i].IsInterface)
						continue;
					Type implementedType = allServerTypes.FirstOrDefault(x => x.GetInterface(allInterfaceTypes[i].Name) != null);
					if (implementedType == null)
						continue;
					ServiceHost host = new ServiceHost(implementedType, new Uri("http://localhost:9988/" + implementedType.Name + ".svc"));
					host.AddServiceEndpoint(allInterfaceTypes[i], wsHttpBinding, "");

					ServiceMetadataBehavior metaDataBehavior = new ServiceMetadataBehavior();
					metaDataBehavior.HttpGetEnabled = true;
					host.Description.Behaviors.Add(metaDataBehavior);
					host.Description.Behaviors.Add(new NHibernateInceptor());
					ServiceDebugBehavior debug = host.Description.Behaviors.Find<ServiceDebugBehavior>();
					if (debug == null)
					{
						host.Description.Behaviors.Add(
							 new ServiceDebugBehavior() { IncludeExceptionDetailInFaults = true });
					}
					else
					{
						if (!debug.IncludeExceptionDetailInFaults)
							debug.IncludeExceptionDetailInFaults = true;
					}


					host.AddServiceEndpoint(typeof(IMetadataExchange), wsHttpBinding, "MEX");
					hosts.Add(host);
					host.Open();

					Console.WriteLine(DateTime.Now.ToString() + " -- Start Service : " + implementedType.Name);

				}

				Console.WriteLine("Server has been started.");
				Console.ReadLine();
			}
			catch (Exception e)
			{
				Console.WriteLine(e.Message);
				Console.WriteLine("Server started fail.");
			}
			finally
			{
				foreach (ServiceHost host in hosts)
				{
					if (host.State == CommunicationState.Opened)
						host.Close();
					else
						host.Abort();
				}
			}

			Console.ReadLine();


		}
	}
}
